#include "ktcpconnection.h"
#include "tool.h"



KTcpConnection::KTcpConnection(QObject *parent)
    : QObject{parent}
{}

KTcpConnection::KTcpConnection(QObject *parent, QString ip, int port): QObject(parent),ip(ip),port(port)
{
    // qDebug()<<"1";
    // qDebug()<<"1111";
    ctool=new class ctool(this);
    clientToServer=new QTcpSocket(this);
    clientToServer->connectToHost(QHostAddress(ip),port);
    connect(clientToServer,&QTcpSocket::readyRead,this,[this](){
        handleServerInfo(clientToServer->readAll());
    });
}

void KTcpConnection::handleServerInfo(QByteArray byteArray)
{
    // qDebug()<<"1111";
    ctool->processingCommunicationInformationCenter(byteArray);
}

bool KTcpConnection::wirteToLogin(QByteArray acc, QByteArray psw, bool isToSaveToLocation)
{

    this->isToSaveToLocation=isToSaveToLocation;
    Tool::getStaticTool()->setIsToSaveToLocation(isToSaveToLocation);
    QJsonObject jsonObj;
    jsonObj.insert("action","Login");
    jsonObj.insert("acc",QString::fromUtf8(acc));
    jsonObj.insert("psw",QString::fromUtf8(psw));
    QJsonDocument jsonDoc(jsonObj);
    // qDebug()<<"1111111111111111";
    clientToServer->write(jsonDoc.toJson()+dedicatedDelimiter);
    return true;
}




int KTcpConnection::getPort() const
{
    return port;
}

void KTcpConnection::setPort(int newPort)
{
    port = newPort;
}

QString KTcpConnection::getIp() const
{
    return ip;
}

void KTcpConnection::setIp(const QString &newIp)
{
    ip = newIp;
}
